'use strict';

const Controller = require('egg').Controller;

class LoginController extends Controller {
  
  async info() {
    const { ctx, service } = this

    if (ctx.session && ctx.session.id) {
      const res = await ctx.service.user.show({_id: ctx.session.id})
      ctx.helper.returnJson({
        ctx,
        data: res
      })
    } else {
      ctx.helper.returnJson({
        ctx,
        msg: '未登录',
        code: 50
      })
    }
  }

  async login() {
    const { ctx, service } = this
    let body = ctx.request.body
    const res = await ctx.service.user.show({username: body.username, password: body.password})
    if (res) {
      ctx.helper.returnJson({
        ctx,
        data: res
      })
      res.id = res._id
      ctx.session = res
    } else {
      ctx.helper.returnJson({
        ctx,
        msg: '用户名或密码错误',
        code: 50
      })
    }
  }

  // 退出登录
  logout () {
    const { ctx } = this
    
    ctx.session = null

    ctx.helper.returnJson({
      ctx,
      data: null
    })
    
  }
}

module.exports = LoginController